package com.usian.skill.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.pojo.OrderInfo;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/skill")
public class SkillController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SkillOrderService skillOrderService;
    @Autowired
    private SkillService skillService;
    @RequestMapping("/skillGood")
    public String skillGood(HttpSession session, Long goodsId, Model model){
        String userId = (String) session.getAttribute("userId");
        if (userId==null){
            return "login";
        }
        //查库存
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount()<=0){
            model.addAttribute("errmsg","库存不足");
            return "miaosha_fail";
        }

        //查看是否秒杀过
        SkillOrder skillOrder = skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery().eq(SkillOrder::getGoodsId, goodsId).eq(SkillOrder::getUserId, userId));
        if (skillOrder!=null){
            model.addAttribute("errmsg","不能重复秒杀");
            return "miaosha_fail";
        }
        //减库存,生成订单
        OrderInfo info = skillService.skill(userId, goodsVo);
        model.addAttribute("goods", goodsVo);
        model.addAttribute("orderInfo",info);
        return "order_detail";
    }
}
